from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from users.models import User
from users.serializers import UserSerializer, UserDetailSerializer, EmailSerializer


class CheckUsername(APIView):
    """验证用户名是否重复"""
    def get(self, request, name):
        """
        验证用户名是否重复
        url(r"usernames/(?P<name>\w+)/count/",views.CheckUsername.as_view()),
        :param request:
        :param name:
        :return:
            "count":count,
            "username":name
        """
        # 1.根据name查询数据库
        count = User.objects.filter(username=name).count()
        return Response({
            "count":count,
            "username":name
        })

class CheckMobileView(APIView):
    """检查手机号是否重复"""
    def get(self,request,mobile):
        """
        检车手机号是否已经存在,返回数量
        :param request:
        :param mobile:
        :return:
            "mobile":mobile
            "count":0
        """
        # 1.根据name查询数据库
        count = User.objects.filter(mobile=mobile).count()
        return Response({
            "count": count,
            "mobile":mobile
        })

class UserView(CreateAPIView):
    """
        实现用户注册功能
        url(r"^users/$", views.UserView.as_view()),
        传入的参数:
            allow: "true"
            mobile: "13711111111"
            password: "11111111"
            password2: "11111111"
            sms_code: "261800"
            username: "python"

    """
    serializer_class = UserSerializer


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]  # 用户验证

    def get_object(self):
        print("get_object返回指定对象:")
        print(self.request.user)
        return self.request.user

class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    permission_classes = [IsAuthenticated]  # 验证用户登录
    serializer_class = EmailSerializer

    def get_object(self, *args, **kwargs):
        """
        重写get_object方法,获取当前用户对象
        :param args:
        :param kwargs:
        :return:
        """
        return self.request.user

class VerifyEmailView(APIView):
    """验证邮箱"""
    def get(self, request):
        """
        验证邮箱,将用户数据中的邮箱状态置为真
        :param request:
        :return:
        """
        # 获取token
        token = request.query_params.get('token')
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({"errors":"token无效"}, status=status.HTTP_400_BAD_REQUEST)

        # 查找用户
        username = data.get("username")
        print("username:{}".format(username))
        try:
            user = User.objects.get(username=username)
        except:
            return Response({"errors":"用户不存在"},status=status.HTTP_400_BAD_REQUEST)

        # 更改用户邮箱验证状态
        user.email_active = True
        user.save()
        return Response({"message":True})





